﻿using log4net;
using log4net.Config;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;


namespace Zero.WebAPI.Framework.Helper
{

    public static class LogHelper
    {
        private static ILog logger;
        static LogHelper()
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
            logger = LogManager.GetLogger(typeof(LogHelper));
        }

        private static string FormatMessage(string message, string sourceFile, int lineNumber, string memberName)
        {
            string fileName = Path.GetFileName(sourceFile);
            return $"[{fileName}:{lineNumber} {memberName}] {message}";
        }

        public static void Info(string message)
        {
            logger.Info(message);
        }

        public static void Debug(string message)
        {
            logger.Debug(message);
        }

        public static void Warn(string message,
            [CallerFilePath] string sourceFile = "",
            [CallerLineNumber] int lineNumber = 0,
            [CallerMemberName] string memberName = "")
        {
            logger.Warn(FormatMessage(message, sourceFile, lineNumber, memberName));
        }

        public static void Error(string message, Exception? ex = null,
            [CallerFilePath] string sourceFile = "",
            [CallerLineNumber] int lineNumber = 0,
            [CallerMemberName] string memberName = "")
        {
            var formatted = FormatMessage(message, sourceFile, lineNumber, memberName);
            if (ex != null)
                logger.Error(formatted, ex);
            else
                logger.Error(formatted);
        }

        public static void Fatal(string message, Exception? ex = null,
            [CallerFilePath] string sourceFile = "",
            [CallerLineNumber] int lineNumber = 0,
            [CallerMemberName] string memberName = "")
        {
            var formatted = FormatMessage(message, sourceFile, lineNumber, memberName);
            if (ex != null)
                logger.Fatal(formatted, ex);
            else
                logger.Fatal(formatted);
        }
    }

}
